package com.atguigu.daijia.customer.service.impl;

import com.atguigu.daijia.common.constant.RedisConstant;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.Result;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.customer.client.CustomerInfoFeignClient;
import com.atguigu.daijia.customer.service.CustomerService;
import com.atguigu.daijia.model.vo.customer.CustomerLoginVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CustomerServiceImpl implements CustomerService {
    @Resource
    private CustomerInfoFeignClient customerInfoFeignClient;
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public String login(String code) {
        //1.拿着code远程调用，拿到id
        Result<Long> loginResult = customerInfoFeignClient.login(code);
        //2.判断如果返回失败，返回错误的提示 //这就是微信登录的好处，匹配的电话号和密码才能查到openid，在customer-service中加了try-catch
        //结合自己写好的枚举类，即可解决账号密码不配的问题，并拿到状态码
        Integer code1 = loginResult.getCode();
        if(200 != code1){
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        //3.获取远程调用的返回的用户id
        Long id = loginResult.getData();
        //4.判断返回用户id是否为空,如果为空，返回错误提示
        if(null == id){
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        //5.生成token
        String token = UUID.randomUUID().toString().replaceAll("-","");
        //6.把用户id放到redis,设置过期时间
        //key:token value:customerId
        //redisTemplate.opsForValue.set(token,customerId.toString(),30,Timeunit.MINUTES)
        redisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_KEY_PREFIX+token,id.toString(),30, TimeUnit.MINUTES);
        //7.返回token
        return token;
    }

    @Override
    public Result<CustomerLoginVo> getCustomerLoginInfo(String token) {

        //1.根据token拿到存在redis中的id
        String customerId = (String)redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX+token);
        if(!StringUtils.hasText(customerId)){
            //登录超时
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        //2.拿到id远程调用service-customer中的方法
        Result<CustomerLoginVo> customerLoginVo = customerInfoFeignClient.getCustomerLoginInfo(Long.parseLong(customerId));
        if(200 != customerLoginVo.getCode()){
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        if(null == customerLoginVo.getData()){
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        //3.返回CustomerLoginVo
        return customerLoginVo;
    }
}
